<!-- HTML header for doxygen 1.8.6-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<title>OpenCV: Back Projection</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<script type="text/javascript" src="../../tutorial-utils.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
//<![CDATA[
MathJax.Hub.Config(
{
  TeX: {
      Macros: {
          matTT: [ "\\[ \\left|\\begin{array}{ccc} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{array}\\right| \\]", 9],
          fork: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ \\end{array} \\right.", 4],
          forkthree: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ \\end{array} \\right.", 6],
          forkfour: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ #7 & \\mbox{#8}\\\\ \\end{array} \\right.", 8],
          vecthree: ["\\begin{bmatrix} #1\\\\ #2\\\\ #3 \\end{bmatrix}", 3],
          vecthreethree: ["\\begin{bmatrix} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{bmatrix}", 9],
          cameramatrix: ["#1 = \\begin{bmatrix} f_x & 0 & c_x\\\\ 0 & f_y & c_y\\\\ 0 & 0 & 1 \\end{bmatrix}", 1],
          distcoeffs: ["(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \\tau_x, \\tau_y]]]]) \\text{ of 4, 5, 8, 12 or 14 elements}"],
          distcoeffsfisheye: ["(k_1, k_2, k_3, k_4)"],
          hdotsfor: ["\\dots", 1],
          mathbbm: ["\\mathbb{#1}", 1],
          bordermatrix: ["\\matrix{#1}", 1]
      }
  }
}
);
//]]>
</script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
<link href="../../stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<!--#include virtual="/google-search.html"-->
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="../../opencv-logo-small.png"/></td>
  <td style="padding-left: 0.5em;">
   <div id="projectname">OpenCV
   &#160;<span id="projectnumber">4.5.2</span>
   </div>
   <div id="projectbrief">Open Source Computer Vision</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
  initMenu('../../',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div id="nav-path" class="navpath">
  <ul>
<li class="navelem"><a class="el" href="../../d9/df8/tutorial_root.html">OpenCV Tutorials</a></li><li class="navelem"><a class="el" href="../../d7/da8/tutorial_table_of_content_imgproc.html">Image Processing (imgproc module)</a></li>  </ul>
</div>
</div><!-- top -->
<div class="header">
  <div class="headertitle">
<div class="title">Back Projection </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p><b>Prev Tutorial:</b> <a class="el" href="../../d8/dc8/tutorial_histogram_comparison.html">Histogram Comparison</a></p>
<p><b>Next Tutorial:</b> <a class="el" href="../../de/da9/tutorial_template_matching.html">Template Matching</a></p>
<table class="doxtable">
<tr>
<th align="right"></th><th align="left"></th></tr>
<tr>
<td align="right">Original author </td><td align="left">Ana Huamán </td></tr>
<tr>
<td align="right">Compatibility </td><td align="left">OpenCV &gt;= 3.0 </td></tr>
</table>
<h2>Goal </h2>
<p>In this tutorial you will learn:</p>
<ul>
<li>What is Back Projection and why it is useful</li>
<li>How to use the OpenCV function <a class="el" href="../../d6/dc7/group__imgproc__hist.html#ga3a0af640716b456c3d14af8aee12e3ca">cv::calcBackProject</a> to calculate Back Projection</li>
<li>How to mix different channels of an image by using the OpenCV function <a class="el" href="../../d2/de8/group__core__array.html#ga51d768c270a1cdd3497255017c4504be">cv::mixChannels</a></li>
</ul>
<h2>Theory </h2>
<h3>What is Back Projection?</h3>
<ul>
<li>Back Projection is a way of recording how well the pixels of a given image fit the distribution of pixels in a histogram model.</li>
<li>To make it simpler: For Back Projection, you calculate the histogram model of a feature and then use it to find this feature in an image.</li>
<li>Application example: If you have a histogram of flesh color (say, a Hue-Saturation histogram ), then you can use it to find flesh color areas in an image:</li>
</ul>
<h3>How does it work?</h3>
<ul>
<li>We explain this by using the skin example:</li>
<li>Let's say you have gotten a skin histogram (Hue-Saturation) based on the image below. The histogram besides is going to be our <em>model histogram</em> (which we know represents a sample of skin tonality). You applied some mask to capture only the histogram of the skin area: <div class="image">
<img src="../../Back_Projection_Theory0.jpg" alt="Back_Projection_Theory0.jpg"/>
<div class="caption">
T0</div></div>
 <div class="image">
<img src="../../Back_Projection_Theory1.jpg" alt="Back_Projection_Theory1.jpg"/>
<div class="caption">
T1</div></div>
</li>
<li>Now, let's imagine that you get another hand image (Test Image) like the one below: (with its respective histogram): <div class="image">
<img src="../../Back_Projection_Theory2.jpg" alt="Back_Projection_Theory2.jpg"/>
<div class="caption">
T2</div></div>
 <div class="image">
<img src="../../Back_Projection_Theory3.jpg" alt="Back_Projection_Theory3.jpg"/>
<div class="caption">
T3</div></div>
</li>
<li>What we want to do is to use our <em>model histogram</em> (that we know represents a skin tonality) to detect skin areas in our Test Image. Here are the steps<ol type="1">
<li>In each pixel of our Test Image (i.e. \(p(i,j)\) ), collect the data and find the correspondent bin location for that pixel (i.e. \(( h_{i,j}, s_{i,j} )\) ).</li>
<li>Lookup the <em>model histogram</em> in the correspondent bin - \(( h_{i,j}, s_{i,j} )\) - and read the bin value.</li>
<li>Store this bin value in a new image (<em>BackProjection</em>). Also, you may consider to normalize the <em>model histogram</em> first, so the output for the Test Image can be visible for you.</li>
<li><p class="startli">Applying the steps above, we get the following BackProjection image for our Test Image:</p>
<div class="image">
<img src="../../Back_Projection_Theory4.jpg" alt="Back_Projection_Theory4.jpg"/>
</div>
</li>
<li>In terms of statistics, the values stored in <em>BackProjection</em> represent the <em>probability</em> that a pixel in <em>Test Image</em> belongs to a skin area, based on the <em>model histogram</em> that we use. For instance in our Test image, the brighter areas are more probable to be skin area (as they actually are), whereas the darker areas have less probability (notice that these "dark" areas belong to surfaces that have some shadow on it, which in turns affects the detection).</li>
</ol>
</li>
</ul>
<h2>Code </h2>
<ul>
<li><b>What does this program do?</b><ul>
<li>Loads an image</li>
<li>Convert the original to HSV format and separate only <em>Hue</em> channel to be used for the Histogram (using the OpenCV function <a class="el" href="../../d2/de8/group__core__array.html#ga51d768c270a1cdd3497255017c4504be">cv::mixChannels</a> )</li>
<li>Let the user to enter the number of bins to be used in the calculation of the histogram.</li>
<li>Calculate the histogram (and update it if the bins change) and the backprojection of the same image.</li>
<li>Display the backprojection and the histogram in windows.</li>
</ul>
</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'><ul>
<li><b>Downloadable code</b>:<ul>
<li>Click <a href="https://github.com/opencv/opencv/tree/master/samples/cpp/tutorial_code/Histograms_Matching/calcBackProject_Demo1.cpp">here</a> for the basic version (explained in this tutorial).</li>
<li>For stuff slightly fancier (using H-S histograms and floodFill to define a mask for the skin area) you can check the <a href="https://github.com/opencv/opencv/tree/master/samples/cpp/tutorial_code/Histograms_Matching/calcBackProject_Demo2.cpp">improved demo</a></li>
<li>...or you can always check out the classical <a href="https://github.com/opencv/opencv/tree/master/samples/cpp/camshiftdemo.cpp">camshiftdemo</a> in samples.</li>
</ul>
</li>
<li><b>Code at glance:</b> <div class="fragment"><div class="line"></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d1/d4f/imgproc_2include_2opencv2_2imgproc_8hpp.html">opencv2/imgproc.hpp</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d6/d87/imgcodecs_8hpp.html">opencv2/imgcodecs.hpp</a>&quot;</span></div><div class="line"><span class="preprocessor">#include &quot;<a class="code" href="../../d4/dd5/highgui_8hpp.html">opencv2/highgui.hpp</a>&quot;</span></div><div class="line"></div><div class="line"><span class="preprocessor">#include &lt;iostream&gt;</span></div><div class="line"></div><div class="line"><span class="keyword">using namespace </span><a class="code" href="../../d2/d75/namespacecv.html">cv</a>;</div><div class="line"><span class="keyword">using namespace </span>std;</div><div class="line"></div><div class="line"><a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> hue;</div><div class="line"><span class="keywordtype">int</span> bins = 25;</div><div class="line"></div><div class="line"><span class="keywordtype">void</span> Hist_and_Backproj(<span class="keywordtype">int</span>, <span class="keywordtype">void</span>* );</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> main( <span class="keywordtype">int</span> argc, <span class="keywordtype">char</span>* argv[] )</div><div class="line">{</div><div class="line">    <a class="code" href="../../d0/d2e/classcv_1_1CommandLineParser.html">CommandLineParser</a> parser( argc, argv, <span class="stringliteral">&quot;{@input |  | input image}&quot;</span> );</div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>( parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;( <span class="stringliteral">&quot;@input&quot;</span> ) );</div><div class="line">    <span class="keywordflow">if</span>( src.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#abbec3525a852e77998aba034813fded4">empty</a>() )</div><div class="line">    {</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;Could not open or find the image!\n&quot;</span> &lt;&lt; endl;</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;Usage: &quot;</span> &lt;&lt; argv[0] &lt;&lt; <span class="stringliteral">&quot; &lt;Input image&gt;&quot;</span> &lt;&lt; endl;</div><div class="line">        <span class="keywordflow">return</span> -1;</div><div class="line">    }</div><div class="line"></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> hsv;</div><div class="line">    <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cvtColor</a>( src, hsv, <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#gga4e0972be5de079fed4e3a10e24ef5ef0aa4a7f0ecf2e94150699e48c79139ee12">COLOR_BGR2HSV</a> );</div><div class="line"></div><div class="line">    hue.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a55ced2c8d844d683ea9a725c60037ad0">create</a>(hsv.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a146f8e8dda07d1365a575ab83d9828d1">size</a>(), hsv.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a8da9f853b6f3a29d738572fd1ffc44c0">depth</a>());</div><div class="line">    <span class="keywordtype">int</span> ch[] = { 0, 0 };</div><div class="line">    <a class="code" href="../../d2/de8/group__core__array.html#ga51d768c270a1cdd3497255017c4504be">mixChannels</a>( &amp;hsv, 1, &amp;hue, 1, ch, 1 );</div><div class="line"></div><div class="line">    <span class="keyword">const</span> <span class="keywordtype">char</span>* window_image = <span class="stringliteral">&quot;Source image&quot;</span>;</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5afdf8410934fd099df85c75b2e0888b">namedWindow</a>( window_image );</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#gaf78d2155d30b728fc413803745b67a9b">createTrackbar</a>(<span class="stringliteral">&quot;* Hue  bins: &quot;</span>, window_image, &amp;bins, 180, Hist_and_Backproj );</div><div class="line">    Hist_and_Backproj(0, 0);</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( window_image, src );</div><div class="line">    <span class="comment">// Wait until user exits the program</span></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>();</div><div class="line"></div><div class="line">    <span class="keywordflow">return</span> 0;</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keywordtype">void</span> Hist_and_Backproj(<span class="keywordtype">int</span>, <span class="keywordtype">void</span>* )</div><div class="line">{</div><div class="line">    <span class="keywordtype">int</span> histSize = <a class="code" href="../../db/de0/group__core__utils.html#gafa99ec4acc4ecb2dc3c2d05da15d0e3f">MAX</a>( bins, 2 );</div><div class="line">    <span class="keywordtype">float</span> hue_range[] = { 0, 180 };</div><div class="line">    <span class="keyword">const</span> <span class="keywordtype">float</span>* ranges = { hue_range };</div><div class="line"></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> hist;</div><div class="line">    <a class="code" href="../../d6/dc7/group__imgproc__hist.html#ga4b2b5fd75503ff9e6844cc4dcdaed35d">calcHist</a>( &amp;hue, 1, 0, <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a>(), hist, 1, &amp;histSize, &amp;ranges, <span class="keyword">true</span>, <span class="keyword">false</span> );</div><div class="line">    <a class="code" href="../../dc/d84/group__core__basic.html#ga1b6a396a456c8b6c6e4afd8591560d80">normalize</a>( hist, hist, 0, 255, <a class="code" href="../../d2/de8/group__core__array.html#ggad12cefbcb5291cf958a85b4b67b6149fa9f0c1c342a18114d47b516a88e29822e">NORM_MINMAX</a>, -1, <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a>() );</div><div class="line"></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> backproj;</div><div class="line">    <a class="code" href="../../d6/dc7/group__imgproc__hist.html#ga3a0af640716b456c3d14af8aee12e3ca">calcBackProject</a>( &amp;hue, 1, 0, hist, backproj, &amp;ranges, 1, <span class="keyword">true</span> );</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( <span class="stringliteral">&quot;BackProj&quot;</span>, backproj );</div><div class="line"></div><div class="line">    <span class="keywordtype">int</span> w = 400, h = 400;</div><div class="line">    <span class="keywordtype">int</span> bin_w = <a class="code" href="../../db/de0/group__core__utils.html#ga085eca238176984a0b72df2818598d85">cvRound</a>( (<span class="keywordtype">double</span>) w / histSize );</div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> histImg = <a class="code" href="../../d3/d63/classcv_1_1Mat.html#a0b57b6a326c8876d944d188a46e0f556">Mat::zeros</a>( h, w, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga88c4cd9de76f678f33928ef1e3f96047">CV_8UC3</a> );</div><div class="line"></div><div class="line">    <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; bins; i++)</div><div class="line">    {</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga07d2f74cadcf8e305e810ce8eed13bc9">rectangle</a>( histImg, <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>( i*bin_w, h ), <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>( (i+1)*bin_w, h - <a class="code" href="../../db/de0/group__core__utils.html#ga085eca238176984a0b72df2818598d85">cvRound</a>( hist.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#aa5d20fc86d41d59e4d71ae93daee9726">at</a>&lt;<span class="keywordtype">float</span>&gt;(i)*h/255.0 ) ),</div><div class="line">                   <a class="code" href="../../d1/da0/classcv_1_1Scalar__.html">Scalar</a>( 0, 0, 255 ), <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ggaf076ef45de481ac96e0ab3dc2c29a777a89c5f6beef080e6df347167f85e07b9e">FILLED</a> );</div><div class="line">    }</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( <span class="stringliteral">&quot;Histogram&quot;</span>, histImg );</div><div class="line">}</div></div><!-- fragment -->  </div> </li>
</ul>
 <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'><ul>
<li><b>Downloadable code</b>:<ul>
<li>Click <a href="https://github.com/opencv/opencv/tree/master/samples/java/tutorial_code/Histograms_Matching/back_projection/CalcBackProjectDemo1.java">here</a> for the basic version (explained in this tutorial).</li>
<li>For stuff slightly fancier (using H-S histograms and floodFill to define a mask for the skin area) you can check the <a href="https://github.com/opencv/opencv/tree/master/samples/java/tutorial_code/Histograms_Matching/back_projection/CalcBackProjectDemo2.java">improved demo</a></li>
<li>...or you can always check out the classical <a href="https://github.com/opencv/opencv/tree/master/samples/cpp/camshiftdemo.cpp">camshiftdemo</a> in samples.</li>
</ul>
</li>
<li><b>Code at glance:</b> <div class="fragment"><div class="line"><span class="keyword">import</span> java.awt.BorderLayout;</div><div class="line"><span class="keyword">import</span> java.awt.Container;</div><div class="line"><span class="keyword">import</span> java.awt.Image;</div><div class="line"><span class="keyword">import</span> java.util.Arrays;</div><div class="line"><span class="keyword">import</span> java.util.List;</div><div class="line"></div><div class="line"><span class="keyword">import</span> javax.swing.BoxLayout;</div><div class="line"><span class="keyword">import</span> javax.swing.ImageIcon;</div><div class="line"><span class="keyword">import</span> javax.swing.JFrame;</div><div class="line"><span class="keyword">import</span> javax.swing.JLabel;</div><div class="line"><span class="keyword">import</span> javax.swing.JPanel;</div><div class="line"><span class="keyword">import</span> javax.swing.JSlider;</div><div class="line"><span class="keyword">import</span> javax.swing.event.ChangeEvent;</div><div class="line"><span class="keyword">import</span> javax.swing.event.ChangeListener;</div><div class="line"></div><div class="line"><span class="keyword">import</span> org.opencv.core.Core;</div><div class="line"><span class="keyword">import</span> org.opencv.core.CvType;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Mat;</div><div class="line"><span class="keyword">import</span> org.opencv.core.MatOfFloat;</div><div class="line"><span class="keyword">import</span> org.opencv.core.MatOfInt;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Point;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Scalar;</div><div class="line"><span class="keyword">import</span> org.opencv.highgui.HighGui;</div><div class="line"><span class="keyword">import</span> org.opencv.imgcodecs.Imgcodecs;</div><div class="line"><span class="keyword">import</span> org.opencv.imgproc.Imgproc;</div><div class="line"></div><div class="line"><span class="keyword">class </span>CalcBackProject1 {</div><div class="line">    <span class="keyword">private</span> Mat hue;</div><div class="line">    <span class="keyword">private</span> Mat histImg = <span class="keyword">new</span> Mat();</div><div class="line">    <span class="keyword">private</span> JFrame frame;</div><div class="line">    <span class="keyword">private</span> JLabel imgLabel;</div><div class="line">    <span class="keyword">private</span> JLabel backprojLabel;</div><div class="line">    <span class="keyword">private</span> JLabel histImgLabel;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keywordtype">int</span> MAX_SLIDER = 180;</div><div class="line">    <span class="keyword">private</span> <span class="keywordtype">int</span> bins = 25;</div><div class="line"></div><div class="line">    <span class="keyword">public</span> CalcBackProject1(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line">        <span class="keywordflow">if</span> (args.length != 1) {</div><div class="line">            System.err.println(<span class="stringliteral">&quot;You must supply one argument that corresponds to the path to the image.&quot;</span>);</div><div class="line">            System.exit(0);</div><div class="line">        }</div><div class="line"></div><div class="line">        Mat src = Imgcodecs.imread(args[0]);</div><div class="line">        <span class="keywordflow">if</span> (src.empty()) {</div><div class="line">            System.err.println(<span class="stringliteral">&quot;Empty image: &quot;</span> + args[0]);</div><div class="line">            System.exit(0);</div><div class="line">        }</div><div class="line"></div><div class="line">        Mat hsv = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.cvtColor(src, hsv, Imgproc.COLOR_BGR2HSV);</div><div class="line"></div><div class="line">        hue = <span class="keyword">new</span> Mat(hsv.size(), hsv.depth());</div><div class="line">        Core.mixChannels(Arrays.asList(hsv), Arrays.asList(hue), <span class="keyword">new</span> MatOfInt(0, 0));</div><div class="line"></div><div class="line">        <span class="comment">// Create and set up the window.</span></div><div class="line">        frame = <span class="keyword">new</span> JFrame(<span class="stringliteral">&quot;Back Projection 1 demo&quot;</span>);</div><div class="line">        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);</div><div class="line">        <span class="comment">// Set up the content pane.</span></div><div class="line">        Image img = HighGui.toBufferedImage(src);</div><div class="line">        addComponentsToPane(frame.getContentPane(), img);</div><div class="line">        <span class="comment">// Use the content pane&#39;s default BorderLayout. No need for</span></div><div class="line">        <span class="comment">// setLayout(new BorderLayout());</span></div><div class="line">        <span class="comment">// Display the window.</span></div><div class="line">        frame.pack();</div><div class="line">        frame.setVisible(<span class="keyword">true</span>);</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keywordtype">void</span> addComponentsToPane(Container pane, Image img) {</div><div class="line">        <span class="keywordflow">if</span> (!(pane.getLayout() instanceof BorderLayout)) {</div><div class="line">            pane.add(<span class="keyword">new</span> JLabel(<span class="stringliteral">&quot;Container doesn&#39;t use BorderLayout!&quot;</span>));</div><div class="line">            <span class="keywordflow">return</span>;</div><div class="line">        }</div><div class="line"></div><div class="line">        JPanel sliderPanel = <span class="keyword">new</span> JPanel();</div><div class="line">        sliderPanel.setLayout(<span class="keyword">new</span> BoxLayout(sliderPanel, BoxLayout.PAGE_AXIS));</div><div class="line"></div><div class="line">        sliderPanel.add(<span class="keyword">new</span> JLabel(<span class="stringliteral">&quot;* Hue  bins: &quot;</span>));</div><div class="line">        JSlider slider = <span class="keyword">new</span> JSlider(0, MAX_SLIDER, bins);</div><div class="line">        slider.setMajorTickSpacing(25);</div><div class="line">        slider.setMinorTickSpacing(5);</div><div class="line">        slider.setPaintTicks(<span class="keyword">true</span>);</div><div class="line">        slider.setPaintLabels(<span class="keyword">true</span>);</div><div class="line">        slider.addChangeListener(<span class="keyword">new</span> ChangeListener() {</div><div class="line">            @Override</div><div class="line">            <span class="keyword">public</span> <span class="keywordtype">void</span> stateChanged(ChangeEvent e) {</div><div class="line">                JSlider source = (JSlider) e.getSource();</div><div class="line">                bins = source.getValue();</div><div class="line">                update();</div><div class="line">            }</div><div class="line">        });</div><div class="line">        sliderPanel.add(slider);</div><div class="line">        pane.add(sliderPanel, BorderLayout.PAGE_START);</div><div class="line"></div><div class="line">        JPanel imgPanel = <span class="keyword">new</span> JPanel();</div><div class="line">        imgLabel = <span class="keyword">new</span> JLabel(<span class="keyword">new</span> ImageIcon(img));</div><div class="line">        imgPanel.add(imgLabel);</div><div class="line"></div><div class="line">        backprojLabel = <span class="keyword">new</span> JLabel();</div><div class="line">        imgPanel.add(backprojLabel);</div><div class="line"></div><div class="line">        histImgLabel = <span class="keyword">new</span> JLabel();</div><div class="line">        imgPanel.add(histImgLabel);</div><div class="line">        pane.add(imgPanel, BorderLayout.CENTER);</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keywordtype">void</span> update() {</div><div class="line">        <span class="keywordtype">int</span> histSize = Math.max(bins, 2);</div><div class="line">        <span class="keywordtype">float</span>[] hueRange = {0, 180};</div><div class="line"></div><div class="line">        Mat hist = <span class="keyword">new</span> Mat();</div><div class="line">        List&lt;Mat&gt; hueList = Arrays.asList(hue);</div><div class="line">        Imgproc.calcHist(hueList, <span class="keyword">new</span> MatOfInt(0), <span class="keyword">new</span> Mat(), hist, <span class="keyword">new</span> MatOfInt(histSize), <span class="keyword">new</span> MatOfFloat(hueRange), <span class="keyword">false</span>);</div><div class="line">        Core.normalize(hist, hist, 0, 255, Core.NORM_MINMAX);</div><div class="line"></div><div class="line">        Mat backproj = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.calcBackProject(hueList, <span class="keyword">new</span> MatOfInt(0), hist, backproj, <span class="keyword">new</span> MatOfFloat(hueRange), 1);</div><div class="line"></div><div class="line">        Image backprojImg = HighGui.toBufferedImage(backproj);</div><div class="line">        backprojLabel.setIcon(<span class="keyword">new</span> ImageIcon(backprojImg));</div><div class="line"></div><div class="line">        <span class="keywordtype">int</span> w = 400, h = 400;</div><div class="line">        <span class="keywordtype">int</span> binW = (int) Math.round((<span class="keywordtype">double</span>) w / histSize);</div><div class="line">        histImg = Mat.zeros(h, w, CvType.CV_8UC3);</div><div class="line"></div><div class="line">        <span class="keywordtype">float</span>[] histData = <span class="keyword">new</span> <span class="keywordtype">float</span>[(int) (hist.total() * hist.channels())];</div><div class="line">        hist.get(0, 0, histData);</div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; bins; i++) {</div><div class="line">            Imgproc.rectangle(histImg, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(i * binW, h),</div><div class="line">                    <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>((i + 1) * binW, h - Math.round(histData[i] * h / 255.0)), <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0, 0, 255), Imgproc.FILLED);</div><div class="line">        }</div><div class="line">        Image histImage = HighGui.toBufferedImage(histImg);</div><div class="line">        histImgLabel.setIcon(<span class="keyword">new</span> ImageIcon(histImage));</div><div class="line"></div><div class="line">        frame.repaint();</div><div class="line">        frame.pack();</div><div class="line">    }</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="keyword">class </span>CalcBackProjectDemo1 {</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keywordtype">void</span> main(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line">        <span class="comment">// Load the native OpenCV library</span></div><div class="line">        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);</div><div class="line"></div><div class="line">        <span class="comment">// Schedule a job for the event dispatch thread:</span></div><div class="line">        <span class="comment">// creating and showing this application&#39;s GUI.</span></div><div class="line">        javax.swing.SwingUtilities.invokeLater(<span class="keyword">new</span> Runnable() {</div><div class="line">            @Override</div><div class="line">            <span class="keyword">public</span> <span class="keywordtype">void</span> run() {</div><div class="line">                <span class="keyword">new</span> CalcBackProject1(args);</div><div class="line">            }</div><div class="line">        });</div><div class="line">    }</div><div class="line">}</div></div><!-- fragment -->  </div> </li>
</ul>
 <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'><ul>
<li><b>Downloadable code</b>:<ul>
<li>Click <a href="https://github.com/opencv/opencv/tree/master/samples/python/tutorial_code/Histograms_Matching/back_projection/calcBackProject_Demo1.py">here</a> for the basic version (explained in this tutorial).</li>
<li>For stuff slightly fancier (using H-S histograms and floodFill to define a mask for the skin area) you can check the <a href="https://github.com/opencv/opencv/tree/master/samples/python/tutorial_code/Histograms_Matching/back_projection/calcBackProject_Demo2.py">improved demo</a></li>
<li>...or you can always check out the classical <a href="https://github.com/opencv/opencv/tree/master/samples/cpp/camshiftdemo.cpp">camshiftdemo</a> in samples.</li>
</ul>
</li>
<li><b>Code at glance:</b> <div class="fragment"><div class="line"><span class="keyword">from</span> __future__ <span class="keyword">import</span> print_function</div><div class="line"><span class="keyword">from</span> __future__ <span class="keyword">import</span> division</div><div class="line"><span class="keyword">import</span> cv2 <span class="keyword">as</span> cv</div><div class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</div><div class="line"><span class="keyword">import</span> argparse</div><div class="line"></div><div class="line"><span class="keyword">def </span>Hist_and_Backproj(val):</div><div class="line">    </div><div class="line">    bins = val</div><div class="line">    histSize = <a class="code" href="../../d1/d10/classcv_1_1MatExpr.html#a6dff8b6e9105b6d817b493e7be157c90">max</a>(bins, 2)</div><div class="line">    ranges = [0, 180] <span class="comment"># hue_range</span></div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    hist = <a class="code" href="../../d6/dc7/group__imgproc__hist.html#ga6ca1876785483836f72a77ced8ea759a">cv.calcHist</a>([hue], [0], <span class="keywordtype">None</span>, [histSize], ranges, accumulate=<span class="keyword">False</span>)</div><div class="line">    <a class="code" href="../../d2/de8/group__core__array.html#ga7bcf47a1df78cf575162e0aed44960cb">cv.normalize</a>(hist, hist, alpha=0, beta=255, norm_type=cv.NORM_MINMAX)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    backproj = <a class="code" href="../../d6/dc7/group__imgproc__hist.html#gab644bc90e7475cc047aa1b25dbcbd8df">cv.calcBackProject</a>([hue], [0], hist, ranges, scale=1)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    <a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;BackProj&#39;</span>, backproj)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    w = 400</div><div class="line">    h = 400</div><div class="line">    bin_w = int(round(w / histSize))</div><div class="line">    histImg = np.zeros((h, w, 3), dtype=np.uint8)</div><div class="line"></div><div class="line">    <span class="keywordflow">for</span> i <span class="keywordflow">in</span> range(bins):</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gac865734d137287c0afb7682ff7b3db23">cv.rectangle</a>(histImg, (i*bin_w, h), ( (i+1)*bin_w, h - int(np.round( hist[i]*h/255.0 )) ), (0, 0, 255), cv.FILLED)</div><div class="line"></div><div class="line">    <a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Histogram&#39;</span>, histImg)</div><div class="line">    </div><div class="line"></div><div class="line"></div><div class="line">parser = argparse.ArgumentParser(description=<span class="stringliteral">&#39;Code for Back Projection tutorial.&#39;</span>)</div><div class="line">parser.add_argument(<span class="stringliteral">&#39;--input&#39;</span>, help=<span class="stringliteral">&#39;Path to input image.&#39;</span>, default=<span class="stringliteral">&#39;home.jpg&#39;</span>)</div><div class="line">args = parser.parse_args()</div><div class="line"></div><div class="line">src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">cv.imread</a>(<a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">cv.samples.findFile</a>(args.input))</div><div class="line"><span class="keywordflow">if</span> src <span class="keywordflow">is</span> <span class="keywordtype">None</span>:</div><div class="line">    <a class="code" href="../../df/d57/namespacecv_1_1dnn.html#a701210a0203f2786cbfd04b2bd56da47">print</a>(<span class="stringliteral">&#39;Could not open or find the image:&#39;</span>, args.input)</div><div class="line">    exit(0)</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line">hsv = <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cv.cvtColor</a>(src, cv.COLOR_BGR2HSV)</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line">ch = (0, 0)</div><div class="line">hue = np.empty(hsv.shape, hsv.dtype)</div><div class="line"><a class="code" href="../../d2/de8/group__core__array.html#ga83b61f9875e6618ee08487b21ec71ab1">cv.mixChannels</a>([hsv], [hue], ch)</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line">window_image = <span class="stringliteral">&#39;Source image&#39;</span></div><div class="line"><a class="code" href="../../d7/dfc/group__highgui.html#ga5afdf8410934fd099df85c75b2e0888b">cv.namedWindow</a>(window_image)</div><div class="line">bins = 25</div><div class="line"><a class="code" href="../../d7/dfc/group__highgui.html#gaf78d2155d30b728fc413803745b67a9b">cv.createTrackbar</a>(<span class="stringliteral">&#39;* Hue  bins: &#39;</span>, window_image, bins, 180, Hist_and_Backproj )</div><div class="line">Hist_and_Backproj(bins)</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(window_image, src)</div><div class="line"><a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">cv.waitKey</a>()</div><div class="line"></div></div><!-- fragment -->  </div> </li>
</ul>
<h2>Explanation </h2>
<ul>
<li>Read the input image:</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    CommandLineParser parser( argc, argv, <span class="stringliteral">&quot;{@input |  | input image}&quot;</span> );</div><div class="line">    Mat src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>( parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;( <span class="stringliteral">&quot;@input&quot;</span> ) );</div><div class="line">    <span class="keywordflow">if</span>( src.empty() )</div><div class="line">    {</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;Could not open or find the image!\n&quot;</span> &lt;&lt; endl;</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;Usage: &quot;</span> &lt;&lt; argv[0] &lt;&lt; <span class="stringliteral">&quot; &lt;Input image&gt;&quot;</span> &lt;&lt; endl;</div><div class="line">        <span class="keywordflow">return</span> -1;</div><div class="line">    }</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <span class="keywordflow">if</span> (args.length != 1) {</div><div class="line">            System.err.println(<span class="stringliteral">&quot;You must supply one argument that corresponds to the path to the image.&quot;</span>);</div><div class="line">            System.exit(0);</div><div class="line">        }</div><div class="line"></div><div class="line">        Mat src = Imgcodecs.imread(args[0]);</div><div class="line">        <span class="keywordflow">if</span> (src.empty()) {</div><div class="line">            System.err.println(<span class="stringliteral">&quot;Empty image: &quot;</span> + args[0]);</div><div class="line">            System.exit(0);</div><div class="line">        }</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">parser = argparse.ArgumentParser(description=<span class="stringliteral">&#39;Code for Back Projection tutorial.&#39;</span>)</div><div class="line">parser.add_argument(<span class="stringliteral">&#39;--input&#39;</span>, help=<span class="stringliteral">&#39;Path to input image.&#39;</span>, default=<span class="stringliteral">&#39;home.jpg&#39;</span>)</div><div class="line">args = parser.parse_args()</div><div class="line"></div><div class="line">src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">cv.imread</a>(<a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">cv.samples.findFile</a>(args.input))</div><div class="line"><span class="keywordflow">if</span> src <span class="keywordflow">is</span> <span class="keywordtype">None</span>:</div><div class="line">    <a class="code" href="../../df/d57/namespacecv_1_1dnn.html#a701210a0203f2786cbfd04b2bd56da47">print</a>(<span class="stringliteral">&#39;Could not open or find the image:&#39;</span>, args.input)</div><div class="line">    exit(0)</div></div><!-- fragment --> </div> <ul>
<li>Transform it to HSV format:</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    Mat hsv;</div><div class="line">    <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cvtColor</a>( src, hsv, <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#gga4e0972be5de079fed4e3a10e24ef5ef0aa4a7f0ecf2e94150699e48c79139ee12">COLOR_BGR2HSV</a> );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        Mat hsv = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.cvtColor(src, hsv, Imgproc.COLOR_BGR2HSV);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">hsv = <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cv.cvtColor</a>(src, cv.COLOR_BGR2HSV)</div></div><!-- fragment --> </div> <ul>
<li>For this tutorial, we will use only the Hue value for our 1-D histogram (check out the fancier code in the links above if you want to use the more standard H-S histogram, which yields better results):</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    hue.create(hsv.size(), hsv.depth());</div><div class="line">    <span class="keywordtype">int</span> ch[] = { 0, 0 };</div><div class="line">    <a class="code" href="../../d2/de8/group__core__array.html#ga51d768c270a1cdd3497255017c4504be">mixChannels</a>( &amp;hsv, 1, &amp;hue, 1, ch, 1 );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        hue = <span class="keyword">new</span> Mat(hsv.size(), hsv.depth());</div><div class="line">        Core.mixChannels(Arrays.asList(hsv), Arrays.asList(hue), <span class="keyword">new</span> MatOfInt(0, 0));</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">ch = (0, 0)</div><div class="line">hue = np.empty(hsv.shape, hsv.dtype)</div><div class="line"><a class="code" href="../../d2/de8/group__core__array.html#ga83b61f9875e6618ee08487b21ec71ab1">cv.mixChannels</a>([hsv], [hue], ch)</div></div><!-- fragment --> </div> <ul>
<li>as you see, we use the function <a class="el" href="../../d2/de8/group__core__array.html#ga51d768c270a1cdd3497255017c4504be">cv::mixChannels</a> to get only the channel 0 (Hue) from the hsv image. It gets the following parameters:<ul>
<li><b>&amp;hsv:</b> The source array from which the channels will be copied</li>
<li><b>1:</b> The number of source arrays</li>
<li><b>&amp;hue:</b> The destination array of the copied channels</li>
<li><b>1:</b> The number of destination arrays</li>
<li><b>ch[] = {0,0}:</b> The array of index pairs indicating how the channels are copied. In this case, the Hue(0) channel of &amp;hsv is being copied to the 0 channel of &amp;hue (1-channel)</li>
<li><b>1:</b> Number of index pairs</li>
</ul>
</li>
<li>Create a Trackbar for the user to enter the bin values. Any change on the Trackbar means a call to the <b>Hist_and_Backproj</b> callback function.</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="keyword">const</span> <span class="keywordtype">char</span>* window_image = <span class="stringliteral">&quot;Source image&quot;</span>;</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5afdf8410934fd099df85c75b2e0888b">namedWindow</a>( window_image );</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#gaf78d2155d30b728fc413803745b67a9b">createTrackbar</a>(<span class="stringliteral">&quot;* Hue  bins: &quot;</span>, window_image, &amp;bins, 180, Hist_and_Backproj );</div><div class="line">    Hist_and_Backproj(0, 0);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        JPanel sliderPanel = <span class="keyword">new</span> JPanel();</div><div class="line">        sliderPanel.setLayout(<span class="keyword">new</span> BoxLayout(sliderPanel, BoxLayout.PAGE_AXIS));</div><div class="line"></div><div class="line">        sliderPanel.add(<span class="keyword">new</span> JLabel(<span class="stringliteral">&quot;* Hue  bins: &quot;</span>));</div><div class="line">        JSlider slider = <span class="keyword">new</span> JSlider(0, MAX_SLIDER, bins);</div><div class="line">        slider.setMajorTickSpacing(25);</div><div class="line">        slider.setMinorTickSpacing(5);</div><div class="line">        slider.setPaintTicks(<span class="keyword">true</span>);</div><div class="line">        slider.setPaintLabels(<span class="keyword">true</span>);</div><div class="line">        slider.addChangeListener(<span class="keyword">new</span> ChangeListener() {</div><div class="line">            @Override</div><div class="line">            <span class="keyword">public</span> <span class="keywordtype">void</span> stateChanged(ChangeEvent e) {</div><div class="line">                JSlider source = (JSlider) e.getSource();</div><div class="line">                bins = source.getValue();</div><div class="line">                update();</div><div class="line">            }</div><div class="line">        });</div><div class="line">        sliderPanel.add(slider);</div><div class="line">        pane.add(sliderPanel, BorderLayout.PAGE_START);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">window_image = <span class="stringliteral">&#39;Source image&#39;</span></div><div class="line"><a class="code" href="../../d7/dfc/group__highgui.html#ga5afdf8410934fd099df85c75b2e0888b">cv.namedWindow</a>(window_image)</div><div class="line">bins = 25</div><div class="line"><a class="code" href="../../d7/dfc/group__highgui.html#gaf78d2155d30b728fc413803745b67a9b">cv.createTrackbar</a>(<span class="stringliteral">&#39;* Hue  bins: &#39;</span>, window_image, bins, 180, Hist_and_Backproj )</div><div class="line">Hist_and_Backproj(bins)</div></div><!-- fragment --> </div> <ul>
<li>Show the image and wait for the user to exit the program:</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( window_image, src );</div><div class="line">    <span class="comment">// Wait until user exits the program</span></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>();</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment">// Use the content pane&#39;s default BorderLayout. No need for</span></div><div class="line">        <span class="comment">// setLayout(new BorderLayout());</span></div><div class="line">        <span class="comment">// Display the window.</span></div><div class="line">        frame.pack();</div><div class="line">        frame.setVisible(<span class="keyword">true</span>);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(window_image, src)</div><div class="line"><a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">cv.waitKey</a>()</div></div><!-- fragment --> </div> <ul>
<li><b>Hist_and_Backproj function:</b> Initialize the arguments needed for <a class="el" href="../../d6/dc7/group__imgproc__hist.html#ga4b2b5fd75503ff9e6844cc4dcdaed35d">cv::calcHist</a> . The number of bins comes from the Trackbar:</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="keywordtype">int</span> histSize = <a class="code" href="../../db/de0/group__core__utils.html#gafa99ec4acc4ecb2dc3c2d05da15d0e3f">MAX</a>( bins, 2 );</div><div class="line">    <span class="keywordtype">float</span> hue_range[] = { 0, 180 };</div><div class="line">    <span class="keyword">const</span> <span class="keywordtype">float</span>* ranges = { hue_range };</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <span class="keywordtype">int</span> histSize = Math.max(bins, 2);</div><div class="line">        <span class="keywordtype">float</span>[] hueRange = {0, 180};</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    bins = val</div><div class="line">    histSize = <a class="code" href="../../d1/d10/classcv_1_1MatExpr.html#a6dff8b6e9105b6d817b493e7be157c90">max</a>(bins, 2)</div><div class="line">    ranges = [0, 180] <span class="comment"># hue_range</span></div></div><!-- fragment --> </div> <ul>
<li>Calculate the Histogram and normalize it to the range \([0,255]\)</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    Mat hist;</div><div class="line">    <a class="code" href="../../d6/dc7/group__imgproc__hist.html#ga4b2b5fd75503ff9e6844cc4dcdaed35d">calcHist</a>( &amp;hue, 1, 0, Mat(), hist, 1, &amp;histSize, &amp;ranges, <span class="keyword">true</span>, <span class="keyword">false</span> );</div><div class="line">    <a class="code" href="../../dc/d84/group__core__basic.html#ga1b6a396a456c8b6c6e4afd8591560d80">normalize</a>( hist, hist, 0, 255, <a class="code" href="../../d2/de8/group__core__array.html#ggad12cefbcb5291cf958a85b4b67b6149fa9f0c1c342a18114d47b516a88e29822e">NORM_MINMAX</a>, -1, Mat() );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        Mat hist = <span class="keyword">new</span> Mat();</div><div class="line">        List&lt;Mat&gt; hueList = Arrays.asList(hue);</div><div class="line">        Imgproc.calcHist(hueList, <span class="keyword">new</span> MatOfInt(0), <span class="keyword">new</span> Mat(), hist, <span class="keyword">new</span> MatOfInt(histSize), <span class="keyword">new</span> MatOfFloat(hueRange), <span class="keyword">false</span>);</div><div class="line">        Core.normalize(hist, hist, 0, 255, Core.NORM_MINMAX);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    hist = <a class="code" href="../../d6/dc7/group__imgproc__hist.html#ga6ca1876785483836f72a77ced8ea759a">cv.calcHist</a>([hue], [0], <span class="keywordtype">None</span>, [histSize], ranges, accumulate=<span class="keyword">False</span>)</div><div class="line">    <a class="code" href="../../d2/de8/group__core__array.html#ga7bcf47a1df78cf575162e0aed44960cb">cv.normalize</a>(hist, hist, alpha=0, beta=255, norm_type=cv.NORM_MINMAX)</div></div><!-- fragment --> </div> <ul>
<li>Get the Backprojection of the same image by calling the function <a class="el" href="../../d6/dc7/group__imgproc__hist.html#ga3a0af640716b456c3d14af8aee12e3ca">cv::calcBackProject</a></li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    Mat backproj;</div><div class="line">    <a class="code" href="../../d6/dc7/group__imgproc__hist.html#ga3a0af640716b456c3d14af8aee12e3ca">calcBackProject</a>( &amp;hue, 1, 0, hist, backproj, &amp;ranges, 1, <span class="keyword">true</span> );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        Mat backproj = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.calcBackProject(hueList, <span class="keyword">new</span> MatOfInt(0), hist, backproj, <span class="keyword">new</span> MatOfFloat(hueRange), 1);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    backproj = <a class="code" href="../../d6/dc7/group__imgproc__hist.html#gab644bc90e7475cc047aa1b25dbcbd8df">cv.calcBackProject</a>([hue], [0], hist, ranges, scale=1)</div></div><!-- fragment --> </div> <ul>
<li>all the arguments are known (the same as used to calculate the histogram), only we add the backproj matrix, which will store the backprojection of the source image (&amp;hue)</li>
<li>Display backproj:</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( <span class="stringliteral">&quot;BackProj&quot;</span>, backproj );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        Image backprojImg = HighGui.toBufferedImage(backproj);</div><div class="line">        backprojLabel.setIcon(<span class="keyword">new</span> ImageIcon(backprojImg));</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    <a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;BackProj&#39;</span>, backproj)</div></div><!-- fragment --> </div> <ul>
<li>Draw the 1-D Hue histogram of the image:</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="keywordtype">int</span> w = 400, h = 400;</div><div class="line">    <span class="keywordtype">int</span> bin_w = <a class="code" href="../../db/de0/group__core__utils.html#ga085eca238176984a0b72df2818598d85">cvRound</a>( (<span class="keywordtype">double</span>) w / histSize );</div><div class="line">    Mat histImg = Mat::zeros( h, w, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga88c4cd9de76f678f33928ef1e3f96047">CV_8UC3</a> );</div><div class="line"></div><div class="line">    <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; bins; i++)</div><div class="line">    {</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga07d2f74cadcf8e305e810ce8eed13bc9">rectangle</a>( histImg, <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>( i*bin_w, h ), <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>( (i+1)*bin_w, h - <a class="code" href="../../db/de0/group__core__utils.html#ga085eca238176984a0b72df2818598d85">cvRound</a>( hist.at&lt;<span class="keywordtype">float</span>&gt;(i)*h/255.0 ) ),</div><div class="line">                   <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>( 0, 0, 255 ), <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ggaf076ef45de481ac96e0ab3dc2c29a777a89c5f6beef080e6df347167f85e07b9e">FILLED</a> );</div><div class="line">    }</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( <span class="stringliteral">&quot;Histogram&quot;</span>, histImg );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <span class="keywordtype">int</span> w = 400, h = 400;</div><div class="line">        <span class="keywordtype">int</span> binW = (int) Math.round((<span class="keywordtype">double</span>) w / histSize);</div><div class="line">        histImg = Mat.zeros(h, w, CvType.CV_8UC3);</div><div class="line"></div><div class="line">        <span class="keywordtype">float</span>[] histData = <span class="keyword">new</span> <span class="keywordtype">float</span>[(int) (hist.total() * hist.channels())];</div><div class="line">        hist.get(0, 0, histData);</div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; bins; i++) {</div><div class="line">            Imgproc.rectangle(histImg, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(i * binW, h),</div><div class="line">                    <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>((i + 1) * binW, h - Math.round(histData[i] * h / 255.0)), <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0, 0, 255), Imgproc.FILLED);</div><div class="line">        }</div><div class="line">        Image histImage = HighGui.toBufferedImage(histImg);</div><div class="line">        histImgLabel.setIcon(<span class="keyword">new</span> ImageIcon(histImage));</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    w = 400</div><div class="line">    h = 400</div><div class="line">    bin_w = int(round(w / histSize))</div><div class="line">    histImg = np.zeros((h, w, 3), dtype=np.uint8)</div><div class="line"></div><div class="line">    <span class="keywordflow">for</span> i <span class="keywordflow">in</span> range(bins):</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#gac865734d137287c0afb7682ff7b3db23">cv.rectangle</a>(histImg, (i*bin_w, h), ( (i+1)*bin_w, h - int(np.round( hist[i]*h/255.0 )) ), (0, 0, 255), cv.FILLED)</div><div class="line"></div><div class="line">    <a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Histogram&#39;</span>, histImg)</div></div><!-- fragment --> </div> <h2>Results </h2>
<p>Here are the output by using a sample image ( guess what? Another hand ). You can play with the bin values and you will observe how it affects the results: </p><div class="image">
<img src="../../Back_Projection1_Source_Image.jpg" alt="Back_Projection1_Source_Image.jpg"/>
<div class="caption">
R0</div></div>
<div class="image">
<img src="../../Back_Projection1_Histogram.jpg" alt="Back_Projection1_Histogram.jpg"/>
<div class="caption">
R1</div></div>
<div class="image">
<img src="../../Back_Projection1_BackProj.jpg" alt="Back_Projection1_BackProj.jpg"/>
<div class="caption">
R2</div></div>
</div></div><!-- contents -->
<!-- HTML footer for doxygen 1.8.6-->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Apr 2 2021 11:36:35 for OpenCV by &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
<script type="text/javascript">
//<![CDATA[
addTutorialsButtons();
//]]>
</script>
</body>
</html>
